#!/bin/bash

# Queue Admin 构建脚本
set -e

echo "🚀 开始构建 Queue Admin 系统..."

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 函数：打印彩色消息
print_message() {
    echo -e "${2}${1}${NC}"
}

# 检查Docker是否安装
if ! command -v docker &> /dev/null; then
    print_message "❌ Docker 未安装，请先安装 Docker" $RED
    exit 1
fi

if ! command -v docker-compose &> /dev/null; then
    print_message "❌ Docker Compose 未安装，请先安装 Docker Compose" $RED
    exit 1
fi

# 清理旧的构建文件
print_message "🧹 清理旧的构建文件..." $YELLOW
rm -rf server/target
rm -rf webapp/dist

# 构建后端
print_message "🔨 构建后端服务..." $BLUE
cd server
if command -v mvn &> /dev/null; then
    mvn clean package -DskipTests
else
    print_message "⚠️  Maven 未安装，使用 Docker 构建..." $YELLOW
    docker run --rm -v "$(pwd)":/usr/src/app -v "$HOME/.m2":/root/.m2 -w /usr/src/app maven:3.8.6-openjdk-18 mvn clean package -DskipTests
fi
cd ..

# 构建前端
print_message "🎨 构建前端服务..." $BLUE
cd webapp
if command -v npm &> /dev/null; then
    npm install
    npm run build
else
    print_message "⚠️  Node.js 未安装，使用 Docker 构建..." $YELLOW
    docker run --rm -v "$(pwd)":/usr/src/app -w /usr/src/app node:18-alpine sh -c "npm install && npm run build"
fi
cd ..

# 构建Docker镜像
print_message "🐳 构建 Docker 镜像..." $BLUE
docker-compose build

print_message "✅ 构建完成！" $GREEN
print_message "📋 可用命令:" $BLUE
echo "  启动服务: docker-compose up -d"
echo "  查看日志: docker-compose logs -f"
echo "  停止服务: docker-compose down"
echo "  开发环境: docker-compose -f docker-compose.dev.yml up -d"
echo ""
print_message "🌐 访问地址:" $BLUE
echo "  前端: http://localhost"
echo "  后端: http://localhost:8080"
echo "  API文档: http://localhost:8080/swagger-ui.html"
